package com.sikadwafastdaisfondturbo.pretloan.ui.process.page

import android.app.Activity
import android.content.Intent
import android.graphics.Camera
import android.net.Uri
import android.provider.MediaStore
import android.view.LayoutInflater
import android.view.View
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import com.sikadwafastdaisfondturbo.pretloan.R
import com.sikadwafastdaisfondturbo.pretloan.databinding.PageOcrPassportBinding
import com.sikadwafastdaisfondturbo.pretloan.pro.ProFragment
import com.sikadwafastdaisfondturbo.pretloan.ui.process.activity.CameraOcrActivity
import com.sikadwafastdaisfondturbo.pretloan.ui.process.activity.ProcessActivity
import com.sikadwafastdaisfondturbo.pretloan.utils.dialog.PhotoDialog
import com.sikadwafastdaisfondturbo.pretloan.utils.event.EventType
import com.sikadwafastdaisfondturbo.pretloan.utils.gilde.ImageUtil
import com.sikadwafastdaisfondturbo.pretloan.utils.http.AppUrls
import com.sikadwafastdaisfondturbo.pretloan.utils.http.AppUrls.addCommonParams
import com.sikadwafastdaisfondturbo.pretloan.utils.http.IHttpCallback
import com.sikadwafastdaisfondturbo.pretloan.utils.imagecovert.ImageConvert
import com.sikadwafastdaisfondturbo.pretloan.utils.log.HHLog
import org.json.JSONObject
import java.io.File

/**
 * Sikadwa
 * @Author wwdeng
 * @CreateTime: 2024/4/19 18:22
 * @Annotation：流程- 证件照 - 护照信息
 */
class OcrPassportPage: ProFragment() {

    lateinit var binding: PageOcrPassportBinding
    //正面照
    private var imgFrontUrl = ""
    //图片选择
    private lateinit var pickMedia: ActivityResultLauncher<PickVisualMediaRequest>
    override fun getRootView(inflater: LayoutInflater): View {
        binding = PageOcrPassportBinding.inflate(inflater)
        return binding.root
    }

    override fun initView() {
        // 1-注册图库组件
        pickMedia = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
            if (uri != null) {
                // 图片处理
                ImageConvert.covert(context = requireContext(), uri = uri) { localPath, bitmap ->
                    if (localPath != null){
                        ImageUtil.instance!!.loadImageUrl(context,binding.imgView,localPath)
                        uploadImageAction(localPath)
                    }
                }
            } else {
                HHLog.e("No media selected")
            }
        }
    }

    override fun initListener() {
        //护照
        binding.imgView.setOnClickListener {
//            if (imgFrontUrl .isNotEmpty()){
//                return@setOnClickListener
//            }
            showPhotoDialog()
        }
        //下一步
        binding.btnNext.setOnClickListener {
            if (imgFrontUrl.isEmpty()){
                showToast(getString(R.string.tips_submit_error))
                return@setOnClickListener
            }
            val params = JSONObject().addCommonParams().apply {
                put("path", AppUrls.PATH.OCR_INFO)
                put("cardType","PASSPORT")//证件类型（PASSPORT、IDCARD、DRIVING、FACE）
                put("cardImgUrl",imgFrontUrl)//证件图片正面
            }
            val act = context as ProcessActivity
            act.submitAction(params)
            addEvent(EventType.CLICK.CLICK_STEP_OCR_PASSPORT_NEXT,"")
        }
    }

    override fun initData() {
    }

    /**
     * 相机、相册选择
     */
    private fun showPhotoDialog(){
        val photoDialog = PhotoDialog(context,"Passport",object : PhotoDialog.IDialogCallback{
            override fun openCamera() {
                addEvent(EventType.CLICK.CLICK_CAMERA,"Passport")
                onOpenCamera()
            }
            override fun openAlbum() {
                addEvent(EventType.CLICK.CLICK_ALBUM,"Passport")
                onOpenAlbum()
            }
        })
        photoDialog.show()
    }

    /**
     * 拍照
     */
    private val takePhotoResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        when (result.resultCode) {
            Activity.RESULT_OK -> {
                HHLog.e(">>>>>>onActivityResult: data = " + result.data)
                val imgPath = result.data!!.getStringExtra("imgLocalPath")
                if (imgPath != null){
                    ImageUtil.instance!!.loadImageUrl(context,binding.imgView,imgPath)
                    uploadImageAction(imgPath)
                }
            }
        }
    }

    /**
     * 打开相机
     */
    private fun onOpenCamera(){
        val intent = Intent(context, CameraOcrActivity::class.java)
        takePhotoResultLauncher.launch(intent)
    }

    /**
     * 打开相册
     */
    private fun onOpenAlbum(){
        pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
    }

    /**
     * 根据uri获取文件路径
     */
    private fun getRealPathFromURI(contentURI: Uri): String? {
        val result: String?
        val cursor = requireContext().contentResolver.query(contentURI, null, null, null, null)
        if (cursor == null) {
            result = contentURI.path
        } else {
            cursor.moveToFirst()
            val idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA)
            result = cursor.getString(idx)
            cursor.close()
        }
        return result
    }


    /**
     * 上传图片
     */
    private fun uploadImageAction(imgPath: String){
        showLoading()
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.FILE)
        uploadFileAction(httpUrl,File(imgPath),object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                imgFrontUrl = data.optJSONObject("obj")!!.optString("url")
                addEvent(EventType.CLICK.CLICK_STEP_OCR_UPLOAD_USE_PHOTO, "Passport Front ：$imgFrontUrl")
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
            }
        })
    }

    override fun onStart() {
        super.onStart()
        addEvent(String.format(EventType.PAGE.PAGE_STEP_OCR_XX_START,"Passport"),"")
    }

    override fun onDestroy() {
        super.onDestroy()
        addEvent(String.format(EventType.PAGE.PAGE_STEP_OCR_XX_END,"Passport"),"")
    }
}